import { PromptAgentQA, UploadFileCollection } from '@/common';
import { IconButton, Iconify, SvgIcon } from '@/components/icon';
import { useSettings } from '@/store/settingStore';
import { useThemeToken } from '@/theme/hooks';
import { ThemeMode } from '@/types/enum';
import type { MenuProps } from 'antd';

import {
  Avatar,
  Button,
  Divider,
  Dropdown,
  Progress,
  Space,
  Splitter,
  Table,
  Tabs,
  message,
} from 'antd';
import { CSSProperties, useEffect, useMemo, useState } from 'react';

import { ColumnsType } from 'antd/es/table';
import { TableProps } from 'antd';
import TabPane from 'antd/es/tabs/TabPane';
import CollectionTable from './CollectionTable';
import { useSearchParams } from 'react-router-dom';

import datasetService from '@/api/services/datasetService';

import { TableRowSelection } from 'antd/es/table/interface';
import { CloseOutlined } from '@ant-design/icons';

type Props = {
  datas: UploadFileCollection[];
  onDelete: (collection: UploadFileCollection, isArr: boolean) => void;
  onUpdate?: (id: string) => void;
} & TableProps;
export default function FileListTable({ datas, onDelete, onUpdate, className }: Props) {
  const { themeMode } = useSettings();
  const { colorPrimary, colorSuccess, colorBgBase, colorBgLayout } = useThemeToken();
  const [searchParams] = useSearchParams();
  const id = searchParams.get('id');
  const parentId = searchParams.get('parentId');

  const iconMap = {
    md: <SvgIcon size="18" icon="ic_file_md" />,
    txt: <SvgIcon size="18" icon="ic_file_txt" />,
    pdf: <SvgIcon size="18" icon="ic_file_pdf" />,
    ppt: <SvgIcon size="18" icon="ic_file_ppt" />,
    pptx: <SvgIcon size="18" icon="ic_file_ppt" />,
    xls: <SvgIcon size="18" icon="ic_file_excel" />,
    xlsx: <SvgIcon size="18" icon="ic_file_excel" />,
    doc: <SvgIcon size="18" icon="ic_file_word" />,
    docx: <SvgIcon size="18" icon="ic_file_word" />,
    file: <SvgIcon size="18" icon="ic_file" />,
    url: <SvgIcon size="18" icon="ic_file" />,
  };

  const getSize = (size: number) => {
    if (size >= 1024 * 1024 * 1024) {
      return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
    } else if (size >= 1024 * 1024) {
      return `${(size / (1024 * 1024)).toFixed(2)} MB`;
    } else if (size >= 1024) {
      return `${(size / 1024).toFixed(2)} KB`;
    } else if (size == 0) {
      return ``;
    } else {
      return `${size} B`;
    }
  };

  // 获取文件名后缀
  const getFileIcon = (name: string) => {
    try {
      const arr = name.split('.');
      return iconMap[arr[arr.length - 1]];
    } catch {
      return iconMap['file'];
    }
  };

  const onRefresh = async (record) => {
    console.log(record);
    const data = {
      datasetId: id,
      fileId: record.fileId,
      name: record.name!,
      chunkSize: 1500,
      chunkSplitter: '',
      qaPrompt: PromptAgentQA.description,
      trainingType: 'chunk',
      preservePdfImages: 'link',
      // preservePdfImages: 'ocr'
    };

    if (parentId) {
      data.parentId = parentId;
    }

    datasetService
      .createDatasetCollection(data)
      .then((res) => {
        message.success('任务重启成功');
        onUpdate && onUpdate(record.fileId);
      })
      .catch((error) => {
        message.error(error?.message);
      });
  };

  // useEffect(() => {
  //   console.log('datas', datas);
  // }, [datas]);

  const columns: ColumnsType<UploadFileCollection> = [
    {
      title: '文件名',
      dataIndex: 'name',
      width: '50%',
      render: (_, record) => (
        <div className="flex items-center">
          {/* <img src={record.avatar} alt="" className="h-9 w-9 rounded-full" /> */}
          <div style={{ flexShrink: 0 }}>{getFileIcon(record.name)}</div>
          <div className="ml-2 flex flex-col">
            <span className="font-semibold">{record.name}</span>
            {/* <span className="text-xs opacity-50">{record.createTime}</span> */}
          </div>
        </div>
      ),
    },
    {
      title: '文件大小',
      dataIndex: 'status',
      width: '10%',
      render: (_, record) => <div>{getSize(record.size)}</div>,
    },
    {
      title: '页数',
      dataIndex: 'pageCount',
      width: '10%',
      render: (_, record) => <div>{record.pageCount ? `共 ${record.pageCount} 页` : '-'}</div>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: '50%',
      render: (_, record) => (
        <div>
          {record.status === 'ready' ? (
            record?.type === 'url' ? (
              '等待导入'
            ) : (
              '等待上传'
            )
          ) : record.status === 'error' ? (
            // <span className="text-error">上传失败</span>
            record?.statusCn ? (
              <span className="text-error">{record.statusCn}</span>
            ) : (
              // 上传失败
              <span className="text-error">上传失败</span>
            )
          ) : (
            <Progress
              percent={record?.percent}
              strokeColor={{ from: colorPrimary, to: '#00D0FE' }}
              trailColor="transparent"
              status="active"
            />
          )}
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '160px',
      render: (_, record) => (
        <div className="flex items-center space-x-2">
          {/* <IconButton>
            <SvgIcon icon="ic-eye" />
          </IconButton>
          <IconButton>
            <SvgIcon icon="ic-edit" />
          </IconButton> */}
          {/* <IconButton
            onClick={() => {
              onDelete(record, false);
            }}
          >
            <SvgIcon icon="ic-delete" />
          </IconButton> */}
          <Button
            onClick={() => {
              onDelete(record, false);
            }}
            type="text"
            disabled={record.isDelete && record.status != 'error'}
            danger>
            <SvgIcon icon="delete-icons" size={16} />
            删除
          </Button>
          {/* {
            (record.status === "error" && record?.fileId)
            &&
            <IconButton onClick={() => { onRefresh(record) }}>
              <SvgIcon icon="ic-retry" size={17}/>
            </IconButton>
          } */}
        </div>
      ),
    },
  ];

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<any> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const selectedItems = useMemo(() => {
    // 创建哈希映射提升查找效率
    const dataMap = new Map(datas.map((item) => [item.uid, item]));

    return selectedRowKeys
      .map((uid) => dataMap.get(uid)) // O(1) 查找
      .filter((item): item is any => !!item); // 类型守卫过滤undefined
  }, [datas, selectedRowKeys]);

  const style: CSSProperties = {
    height: '100%',
    padding: '16px',
    borderRadius: '16px',
    backgroundColor: themeMode === ThemeMode.Light ? colorBgLayout : 'rgba(145, 158, 171, 0.12)',
  };
  return (
    <>
      <Table
        rootClassName="rounded-e-md"
        bordered={false}
        // showHeader={false}
        size="small"
        className={className}
        rowKey={'uid'}
        rowSelection={{ ...rowSelection }}
        columns={columns}
        dataSource={datas}
      />

      {selectedRowKeys.length > 0 && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={() => {
                setSelectedRowKeys([]);
              }}
            />
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRowKeys.length} 项
            </span>
            <Splitter />

            <Button
              style={{ color: '#fff' }}
              type="text"
              onClick={() => {
                if (selectedItems.length === 0) return;
                onDelete(selectedItems, true);
                setSelectedRowKeys([]);
                // onDelete(selectedRowKeys);
              }}
            >
              删除
            </Button>
          </Space>
        </div>
      )}
    </>
  );
}
